package com.yan.demo.demo4;

import java.util.SplittableRandom;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author taoge
 * @Date 2024/8/7 18:31
 * @Description 1.设计一个多线程的程序如下：设计一个火车售票模拟程序。
 * 假如火车站要有100张火车票要卖出，现在有5个售票点同时售票，用5个线程模拟这5个售票点的售票情况。
 */
public class Test4 {
    public static void main(String[] args) {
        MyTask4 myTask4 = new MyTask4();
        String[] name = {"A窗口","B窗口","C窗口"};
        Thread t1 = new Thread(myTask4 ,"A窗口");
        Thread t2 = new Thread(myTask4 ,"B窗口");
        Thread t3 = new Thread(myTask4 ,"C窗口");
        //Thread t4 = new Thread(myTask4 ,"D窗口");
        //Thread t5 = new Thread(myTask4 ,"E窗口");
        /*t1.start();
        t2.start();
        t3.start();*/
        //t4.start();
        //t5.start();
        for (int i = 0; i < 3; i++) {
            new Thread(myTask4 , name[i]).start();
        }
    }
}

class MyTask4 implements Runnable{

     private  int num  = 100;
     Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while(true){
            try {
                lock.lock();
                if(num <= 0){
                    System.out.println("票卖完了");
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "窗口卖出了第" + num +"张票");
                num --;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

